#!/usr/bin/python
"""Connand-line script to hook you up to the MUD of your choice."""
from mudpyl import __version__

import argparse

parser = argparse.ArgumentParser(version = "%(prog)s " + __version__, 
                                 prog = 'mudpyl')

known_uis = ['gtk','text']
ui_help = ("The UI to use. Available options: %s. Default: %%(default)s" %
                     ', '.join(known_uis))

parser.add_argument('-u', '--ui', default = 'text', help = ui_help,
                    choices = known_uis)
parser.add_argument("modulename", help = "The module to import")
parser.add_argument("--profile", action = "store_true",  default = False,
                    help = "Whether to profile exection. Default: False")

UI_PREFIX='mudpyl.ui.'


def main():
    """Launch the client.

    This is the main entry point. This will first initialise the GUI, then
    load the main module specified on the command line.
    """
    options = parser.parse_args()

    from mudpyl.modules import load_file
    modclass = load_file(options.modulename)

    UI_full_path='{prefix}{name}ui.{name}ui'.format(prefix=UI_PREFIX,name=options.ui)
    UI_module=__import__(UI_full_path,globals(),locals(),[options.ui])

    UI_module.reactor_install()

    from twisted.internet import reactor

    from mudpyl.net.telnet import TelnetClientFactory
    factory = TelnetClientFactory(modclass.name, modclass.encoding,
                                  options.modulename)


    modinstance = factory.realm.load_module(modclass)
    modinstance.is_main()


    UI_module.configure(factory.realm)


    factory.doStart()

    #pylint kicks up a major fuss about these lines, but that's because 
    #Twisted does some hackery with the reactor namespace.
    #pylint: disable-msg=E1101

    reactor.connectTCP(modclass.host, modclass.port, factory)
    print 'connected'
    if not options.profile:
        reactor.run()
    else:
        import cProfile
        cProfile.runctx("reactor.run()", globals(), locals(),
                        filename = "mudpyl.prof")

if __name__ == '__main__':
    main()
